﻿using System.Collections.Generic;
using System.Drawing;
using NeuronDotNet.Controls;

namespace NeuronDotNet.Samples.CharacterRecognition
{
    internal class Words
    {
        internal List<Letter> GetLetters(Letter letter)
        {
            List<Rectangle> rectangles = FindRectangles(letter);
            List<Letter> letters = new List<Letter>();

            foreach (Rectangle rectangle in rectangles)
            {
                Letter newLetter = new Letter(letter);
                newLetter.Clip(rectangle);
                letters.Add(newLetter);
            }

            return letters;
        }

        private List<Rectangle> FindRectangles(Letter letter)
        {
            Bitmap letterBitmap = GetBitmap(letter);

            List<Rectangle> rectangles = new List<Rectangle>();
            int width = 0;
            bool previousWhite = true;

            for (int i = 0; i < letterBitmap.Width; i++)
            {
                bool currentWhite = true;
                for (int j = 0; j < letterBitmap.Height; j++)
                {

                    if (letterBitmap.GetPixel(i, j).R != 255 && letterBitmap.GetPixel(i, j).G != 255 && letterBitmap.GetPixel(i, j).B != 255)
                    {
                        currentWhite = false;
                        previousWhite = false;
                        width++;
                        break;
                    }
                }

                if ((currentWhite && !previousWhite) || ((i == letterBitmap.Width - 1) && !previousWhite))
                {
                    int start = i - width;
                    rectangles.Add(new Rectangle(start + letter.left, letter.top, width, letterBitmap.Height));
                    width = 0;
                    previousWhite = true;
                }
            }

            return rectangles;
        }

        public Bitmap GetBitmap(Letter letter)
        {
            int width = letter.right - letter.left;
            int height = letter.bottom - letter.top;

            double[] bitArray = letter.GetEquivalentVector(height, width);
            Bitmap letterBitmap = new Bitmap(width, height);

            int k = 0;
            for (int i = 0; i < height; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    int darkness = (int)((1 - bitArray[k++]) * 255);
                    letterBitmap.SetPixel(j, i, Color.FromArgb(darkness, darkness, darkness));
                }
            }

            return letterBitmap;
        }
    }
}
